<template>
	<div class="content-box">
		<el-row :gutter="10" class="head-row">
			<el-col :span="20" class="firstcol">
				<el-button disabled style="margin-right: 0.625rem;" type="text">根据日期筛选数据</el-button>
				<el-date-picker v-model="startDate" type="date" placeholder="开始日期" style="margin-right: 0.625rem;"
					clearable @change="changeStart">
				</el-date-picker>
				<el-date-picker v-model="endDate" type="date" placeholder="结束日期" clearable
					style="margin-right: 0.625rem;" @change="changeEnd">
				</el-date-picker>
			</el-col>
		</el-row>
		

		<div class="ceshibox">
			
			<p>
				<vxe-radio-group v-model="selectTab" @change="changeTab">
					<vxe-radio-button v-for="item, index in tableData.filter((res) => { return !res.is_materials })"
						:label="item.id" :content="item.name" :key="index"></vxe-radio-button>
					<vxe-radio-button v-for="item, index in tableData.filter((res) => { return res.is_materials })"
						:label="item.id" :content="item.name" :key="index"></vxe-radio-button>
				</vxe-radio-group>
			</p>

			<div v-if="tableData.filter((res) => { return res.id == selectTab }).length">
				<!-- <div>{{tableData.filter((res) => { return res.id == selectTab })}}</div> -->
			<div v-for="item, index in tableData.filter((res) => { return !res.is_materials })"
				v-show="selectTab === item.id" :key="index">
				<el-button @click="handleDao">导出excel</el-button>
				<el-button @click="getData">刷新数据</el-button>
				<vxe-table resizable show-overflow ref="xTree" keep-source :sync-resize="selectTab"
					@cell-click="cellClickEvent" @edit-closed="kkk"
					:tree-config="{ children: 'children', showIcon: 'true', expandAll: 'true', reserve: true }"
					highlight-current-row
					:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }"
					:data="tableData1(item.id)">
					<vxe-table-column type="seq" width="60"></vxe-table-column>
					<vxe-table-column field="name" title="类目" tree-node width="200">
					</vxe-table-column>
					<vxe-table-column v-for="(item, index) in placelist" :title="item.name"
						:field="'maindata[' + index + '].money'" :edit-render="{ name: 'input' }" :key="index">
					</vxe-table-column>
					<vxe-table-column title="预算、测算总金额" field="predict_money">
					</vxe-table-column>
					<vxe-table-column title="动态累计发生金额" type="number" field="count_Amount">
						<template v-slot="{ row }">
							<span>{{ countAmount(row) }} 元</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="剩余金额" field="over_money">
						<template v-slot="{ row }">
							<span>{{ leaveAmount(row) }} 元</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="备注" field="remarks.remark" :edit-render="{}">
						<template #edit="{ row }">
							<vxe-input v-model="row.remarks.remark" type="text" @blur="changeRemark(row.remarks)"></vxe-input>
						</template>
					</vxe-table-column>
				</vxe-table>
				
			</div>

			</div>
			<div v-else style="text-align:center;font-size:7vh;color:gray">该时段数据为空</div>

			<div v-if="tableData.filter((res) => { return res.id == selectTab }).length"></div>
			<div v-for="item, index in  tableData.filter((res) => { return res.is_materials })"
				v-show="selectTab === item.id" :key="index">
				<div v-if="tableData.filter((res) => { return res.id == selectTab }).length">
					<el-button @click="handleDaos">导出excel</el-button>
					<el-button @click="getData">刷新数据</el-button>
				<vxe-table resizable show-overflow ref="xTree2" keep-source :sync-resize="selectTab"
					:tree-config="{ children: 'children', showIcon: 'true', expandAll: 'true', reserve: true }"
					@cell-click="cellClickEvent" @edit-closed="kkk" highlight-current-row
					:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }"
					:data="tableData1(item.id)">
					<vxe-table-column type="seq" width="60"></vxe-table-column>
					<vxe-table-column field="name" title="类目" tree-node width="200" height="300">


						</vxe-table-column>

					<vxe-table-colgroup v-for="(item, index) in placelist" :title="item.name" :key="index">
						<vxe-table-column title="金额" :field="'maindata[' + index + '].money'"
							:edit-render="{ name: 'input' }">
						</vxe-table-column>
						<vxe-table-column title="数量" :field="'maindata[' + index + '].num'"
							:edit-render="{ name: 'input' }">
						</vxe-table-column>
					</vxe-table-colgroup>


					<vxe-table-column title="预算、测算总金额" field="predict_money">
					</vxe-table-column>
					<vxe-table-column title="预算、测算总工程量" field="predict_do">
					</vxe-table-column>
					<vxe-table-column title="动态累计发生工程量汇总" field="total_do">
						<template v-slot="{ row }">
							<span>{{ totalnum(row) }}</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="动态累计发生金额" type="number" field="total_money">
						<template v-slot="{ row }">
							<span>{{ totalmoney(row) }} 元</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="剩余工程量" field="over_do">
						<template v-slot="{ row }">
							<span>{{ leaveNum(row) }}</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="剩余金额" field="over_money">
						<template v-slot="{ row }">
							<span>{{ leaveAmount(row) }} 元</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="备注" field="remarks.remark" :edit-render="{}">
						<template #edit="{ row }">
							<vxe-input v-model="row.remarks.remark" type="text" @blur="changeRemark(row.remarks)"></vxe-input>
						</template>
					</vxe-table-column>
				</vxe-table>

				</div>
				<div v-else style="text-align:center;font-size:7vh;color:gray">该时段数据为空</div>
			</div>
		</div>
	</div>
</template>

<script>
import {
	getArticalData,
	UpdateArticalData,
	UpdateRemarkData,
} from "../../api/article";

const XEUtils = require('xe-utils')
export default {
	name: "VueElementAdminIndex",
	data() {
		return {
			pickerOptions0: {
				disabledDate: time => {
					if (this.startDate) {
						return time.getTime() < this.startDate
					}
				}
			},
			end_Date: {
				disabledDate: time => {
					if (this.startDate) {
						return time.getTime() <= this.startDate
					}
				}
			},
			showheader: "false",
			smallActive: "tujian",
			tabPosition: "top",
			keyword: "",
			moduleslist: [],
			keyword: "",
			tableData: [],
			// tableDataC: [],
			placelist: [],
			pid: 15,
			selectTab: '',
			isShow: false,
			startDate: '',
			endDate: '',
			currentDate: new Date(),
			rowData: [],
			nameDisabled: false,
			upData: [],		//旧的数据，用于比较新旧数据，避免不必要的请求。	
			// startDate:"",
			// endDate:"",
			timeMan:"",
		};
	},
	created() {
		// this.startDate = this.$route.query.createTime
		var pro_id = this.$route.query.project_id
		this.pid = pro_id
		this.startDate = this.dealTime(new Date())
		this.endDate = this.startDate
		this.getData();

	},
	mounted() {
		console.log(this.$route.query)
		var pro_id = this.$route.query.project_id
		this.pid = pro_id
	},
	methods: {
		//修改备注
		async changeRemark(res) {
			await UpdateRemarkData(res)
		},
		//禁止编辑
		activeCellMethod({ row, rowIndex }) {
			console.log('Bianji', row);
			this.upData = []
			row.maindata.forEach((res) => {
				this.upData.push({ ...res })
			})
			// if (row.level == 1) {
			if (row.children !== undefined||!row.id) {
				this.$XModal.message({
					message: '禁止编辑',
					status: 'error'
				})
				return false
			}

			if (this.startDate != this.endDate || this.startDate > this.dealTime(this.currentDate)) {
				console.log(this.startDate, this.dealTime(this.currentDate))
				this.$XModal.message({
					message: '禁止编辑，确保表单时间范围为一天',
					status: 'error'
				})
				return false
			}
			// if (row.level == 2 && row.children !== undefined) {
			// 	return false
			// }
			return true
		},
		// //数据合并
		countAmount(row) {
			return XEUtils.sum(row.maindata, 'money')
		},
		leaveAmount(row) {
			// let newresult = Number(row.predict_money) - Number(this.countAmount(row))
			let newresult = Number(row.predict_money) - Number(row.totalmoney)
			return newresult.toFixed(2)
		},

		//材料表相关
		totalnum(row) {
			return XEUtils.sum(row.maindata, 'num')
		},
		totalmoney(row) {
			return XEUtils.sum(row.maindata, 'money')
		},
		leaveNum(row) {
			// let newresult = Number(row.predict_do) - Number(this.totalnum(row))
			let newresult = Number(row.predict_do) - Number(row.totalnum)
			return newresult
		},
		//获取当日数据
		getCurrentData() {
			this.getData()
		},
		//点击单元格触发@cell-click="cellDown"
		cellClickEvent(row) {
			console.log(row);
			this.rowData = row.row.maindata
		},
		//单元格失去焦点时修改
		async kkk(row, rowIndex) {
			const arr = this.rowData
			let list = row.row.maindata
			var objNum = {}
			var isExist = false;
			// console.log(this.upData, "uouououououo	")
			for (var i = 0; i < list.length; i++) {
				var obj = list[i];
				var money = obj.money;
				var num = obj.num;
				// var isExist = false;
				// console.log(this.upData)
				for (var j = 0; j < this.upData.length; j++) {
					if (this.upData[i].money != money || this.upData[i].num != num) {
						const res = await UpdateArticalData(obj)
						if (res.code === 200) {
							isExist = true
						}else{
							// console.log(list[i].id)
							// var templist = this.tableDataa.filter((res) => { return res.id == this.selectTab })[0]
							// var resultObj = this.tableData.filter((res) => { return res.id == this.selectTab })[0]
							// console.log(resultObj,280)
							// function findchild(aimlist){	//寻找修改前该id所对应的数据
							// 	aimlist.forEach((res1,index1)=>{
							// 		resultObj = resultObj[index1]
							// 		console.log(resultObj,284)
							// 		if(res1.children){
							// 			findchild(res1.children)
							// 		}
							// 		if(res1.maindata.some((item)=>{return (item.id) == list[i].id})){
							// 			res1.maindata.map((item,index2)=>{
							// 				if(item.id == list[i].id){
							// 					resultObj = resultObj[index2]
							// 					console.log(resultObj)
							// 					resultObj.money = item.money
							// 					resultObj.num = item.num
							// 				}
							// 			})
							// 			return true
							// 		}
							// 	})
							// }
							// if(templist.children){
							// 	resultObj = resultObj.children
							// 	findchild(templist.children)
							// }else{
							// 	resultObj = [resultObj]
							// 	console.log([templist])
							// 	// findchild([templist])
							// }
							
							// console.log(resultObj)

							// console.log(this.tableDataa.filter((rr)=>{return rr.maindata.some((rrr)=>{return rrr.id == list[i].id})}))
							this.$XModal.message({
							message: res.message,
							status: 'error'
						})
						return false
						}
					}
					// var aj = arr[j];
					// var n = aj.money;
					// if (n == money) {
					// 	isExist = true; 
					// 	break;
					// }
					// objNum = obj
				}
			}
			if (isExist) {
				window.clearTimeout(this.timeMan)
				this.timeMan = window.setTimeout(()=>{
					this.getData()
				},30000)		//三十秒后自动刷新
				
			}
			// console.log(list);
			// const res = await UpdateArticalData(objNum)
			// if (res.code === 200) {
			// 	return this.$message.success('修改成功')
			// }
		},
		//初始获取数据
		async getData() {
			// if(this.endDate ==''){
			// 	const res = await getArticalData({
			// 		project_id: this.pid,
			// 		day_id:currentDate
			// 	});
			// }
			const res = await getArticalData({
				project_id: this.pid,
				start_day: this.startDate,
				end_day: this.endDate,
				day_id: '',

			});

			console.log(res);
			this.tableData = res.moduleslist
			this.tableDataa = JSON.parse(JSON.stringify(res.moduleslist))
			//
			this.moduleslist = res.moduleslist
			this.placelist = res.placelist
			if (res.moduleslist.length && !this.selectTab) {
				this.selectTab = res.moduleslist[0].id
			}
			this.$refs.xTree.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
			this.$refs.xTree2.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})

		},

		changeTab() {
			this.$refs.xTree.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
			this.$refs.xTree2.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
		},

		//将date类型的数据处理成yyyy-mm-dd类型的数据
		dealTime(res) {
			var dateList = {
				y: res.getFullYear(),
				M: res.getMonth() + 1,
				d: res.getDate(),
			}
			if (String(dateList["M"]).length == 1) {
				dateList["M"] = '0' + dateList["M"]
			}
			if (String(dateList["d"]).length == 1) {
				dateList["d"] = '0' + dateList["d"]
			}
			return dateList["y"] + "-" + dateList["M"] + "-" + dateList["d"]
		},

		changeStart(res) {
			if (!res) {
				this.startDate = ""
				this.getData()
				return false
			}
			this.startDate = this.dealTime(res)
			this.getData()
		},
		changeEnd(res) {
			if (!res) {
				this.endDate = ""
				this.getData()
				return false
			}
			this.endDate = this.dealTime(res)
			this.getData()
		},


		handleDao(){
			this.$refs.xTree[0].exportData({
				filename: "字段",
				type: "xlsx",
				useStyle: true,
				data: this.exportData
			})
		},

		handleDaos(){
			this.$refs.xTree2[0].exportData({
				filename: "字段",
				type: "xlsx",
				useStyle: true,
				data: this.exportData
			})
		},

		seqMethod({row,rowIndex}){
			if(!row.id){
				return "#"
			}else{
				return rowIndex
			}
		},

	},
	computed: {
		//生成包括统计结果的数据
		tableData1() {
			return function (aimid) {

				var resItem = this.tableData.filter((res) => { return res.id == aimid })

				var temp = []
				var total_predict_do = 0
				var total_predict_money = 0
				var total_over_do = 0
				var total_over_money = 0
				var total_num = 0
				var total_num2 = 0
				var totalSquare = 0
				this.placelist.forEach((res) => {
					if (res.square) {
						totalSquare += (res.square)
					}
				})
				resItem.forEach((item, index) => {
					console.log(item.predict_do - item.totalnum)

					if (item.predict_do) {
						total_predict_do += item.predict_do
					}
					if (item.predict_money) {
						total_predict_money += item.predict_money
					}
					if (item.over_do) {
						total_over_do += item.predict_do - item.totalnum
					}
					if (item.over_money) {
						total_over_money += item.predict_money - item.totalmoney
					}
					if (!index) {
						temp = item.maindata
					} else {
						for (var i = 0; i < temp.length; i++) {
							if (item.maindata[i].money) {

								if (item.maindata[i].num) {
									total_num += item.maindata[i].num
									total_num2 += item.maindata[i].num / res.placelist[i].square
									temp[i].money = Number(temp[i].money) + Number(item.maindata[i].num) * Number(item.maindata[i].money)
								} else {
									temp[i].money = Number(temp[i].money) + Number(item.maindata[i].money)
								}
							}

						}
					}
					
				})
				var tempa = JSON.parse(JSON.stringify(temp))        //总造价指标
				this.placelist.forEach((res, index) => {
					tempa[index].money = (temp[index].money / Number(res.square)).toFixed(2)
				})
				var restemp = []
				this.moduleslista = ["总计造价", "总计单方造价（指标）"]
				this.moduleslist = [...this.moduleslista,"总计造价", "总计单方造价（指标）"]

				total_predict_do = total_predict_do.toFixed(2)
				total_predict_money = total_predict_money.toFixed(2)
				total_over_do = total_over_do.toFixed(2)
				total_over_money = total_over_money.toFixed(2)
				total_num = total_num.toFixed(2)
				total_num2 = total_num2.toFixed(2)
				totalSquare = totalSquare.toFixed(2)

				console.log( total_over_money)
				for (var i = 0; i < 2; i++) {
					if (i == 0) {
						restemp.push({ name: this.moduleslista[i], maindata: temp, predict_do: total_predict_do, predict_money: total_predict_money, totalnum:total_over_do, totalmoney: total_over_money, total_num })
					} else {
						restemp.push({ name: this.moduleslista[i], maindata: tempa, predict_do: (total_predict_do / totalSquare).toFixed(2), predict_money: (total_predict_money / totalSquare).toFixed(2), total_num: total_num2, totalmoney: total_over_money,totalnum: total_over_do })
					}
				}
				

				var temp = [...resItem]
				var showDetail = (totalList) => {
				totalList.map((item)=>{
				item["count_Amount"] = this.countAmount(item)
				item["over_money"] = this.leaveAmount(item)
				item["total_do"] = this.totalnum(item)
				item["total_money"] = this.totalmoney(item)
				item["over_do"] = this.leaveNum(item)
				if(item.children){
					showDetail(item.children)
				}
			})
			}
			showDetail(temp)

			console.log(restemp)
			console.log([...temp,...restemp])

			return [...temp,...restemp]



			}
		}
	}
};
</script>	

<style lang="scss" scoped>
.content-box {
	width: 100%;

	.content-table {
		width: 96%;
		margin: 0 auto;
		margin-bottom: 1.25rem;
	}

	.head-row {
		margin-top: 1.25rem;
		margin-left: 1.75rem;
		margin-bottom: 1.25rem;

		.el-col {
			margin-left: 1.75rem;
		}
	}

	.upplace {
		padding: 5px 0
	}
}
</style>
